package com.cgly.medical.controller;

import com.cgly.medical.config.XDelayedMessageConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wangxiangli
 * @create 2022-08-22-16:32
 */
@RestController
@RequestMapping("/delayed")
public class DelayedSendMessageController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendManyMessage")
    public String sendManyMessage(){

        send("延迟消息睡10秒",10000);
        send("延迟消息睡2秒",2000);
        send("延迟消息睡5秒",5000);
        return "success";
    }

    private void send(String msg, Integer delayTime){
        //将消息携带路由键值，异步发送

        rabbitTemplate.convertAndSend(
                XDelayedMessageConfig.DELAYED_EXCHANGE,
                XDelayedMessageConfig.ROUTING_KEY,
                msg,
                message->{
                    //这里设置延迟的时间，然后把msg的内容进行返回，给到监听延迟队列的方法去
                    //其实也就是消费者
                    message.getMessageProperties().setDelay(delayTime);
                    return message;
                });
    }
}
